import os
from z_tdx.lc5_mootdx import read_lc_to_df, bfq_to_qfq, write_df_to_lc

# 左边是源数据文件夹，右边是目标数据文件夹
FILE_PATH = {
    './_cache/lc5/sh': './_cache/_lc5_qfq/sh',
    './_cache/lc5/sz': './_cache/_lc5_qfq/sz',
}


def extract_six_digits(s):
    digit_sequence = []
    for char in s:
        if char.isdigit():
            digit_sequence.append(char)
            # 当收集到6位数字时，返回结果
            if len(digit_sequence) == 6:
                return ''.join(digit_sequence)
        else:
            # 遇到非数字字符则重置序列
            digit_sequence = []
    # 如果没有找到连续6位数字，返回None
    return None


def scan():
    for source in FILE_PATH.keys():
        target = FILE_PATH[source]
        if not os.path.exists(source):
            print(f"错误: 路径 '{source}' 不存在")
            return

        if not os.path.isdir(source):
            print(f"错误: '{source}' 不是一个目录")
            return

        for root, dirs, files in os.walk(source):
            for file in files:
                file_path = os.path.join(root, file)

                df = read_lc_to_df(file_path)
                symbol = extract_six_digits(file)
                df = bfq_to_qfq(df, symbol)
                # print(df)

                target_path = os.path.join(target, file)
                if not os.path.exists(target):
                    os.makedirs(target)
                write_df_to_lc(df, target_path, mode='wb')
                print(f'{file_path} -> {target_path}')


if __name__ == '__main__':
    from tools.utils_basic import pd_show_all
    pd_show_all()

    from warnings import simplefilter
    simplefilter(action='ignore', category=FutureWarning)

    scan()
